﻿using Microsoft.Extensions.DependencyInjection;
using WeDonekRpc.Client.Interface;

namespace WeDonekRpc.NetCoreModular
{
    internal class IocServiceScope : IServiceScope
    {
        private readonly ScopeProvider _Service;
        public IocServiceScope ( IScoreService scope )
        {
            this._Service = new ScopeProvider(scope);
        }

        public IServiceProvider ServiceProvider => this._Service;

        public void Dispose ()
        {
            this._Service.Dispose();
        }
        internal class ScopeProvider : IServiceProvider, IDisposable
        {
            private readonly IScoreService _Ioc;

            internal ScopeProvider ( IScoreService ioc )
            {
                this._Ioc = ioc;
            }

            public void Dispose ()
            {
                this._Ioc.Dispose();
                GC.SuppressFinalize(this);
            }

            public object? GetService ( Type serviceType )
            {
                if ( !this._Ioc.IsRegistered(serviceType) )
                {
                    return null;
                }
                return this._Ioc.Resolve(serviceType);
            }
        }
    }
}
